package com.dhl.commonutils.security;

import com.dhl.commonutils.exception.UserContLockedException;
import com.dhl.entity.SysUser;
import com.dhl.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义登录处理器
 *
 * @title: MyUserDetalisServviceImpl
 * @Author danghailiang
 * @Date: 2022/10/14 22:32
 * @Version 1.0
 */
@Service
@Slf4j
public class MyUserUserDetailsServiceImpl implements UserDetailsService {
    /**
     * 用户服务
     */
    @Resource
    private SysUserService sysUserService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = sysUserService.getSysUserByUsername(username);
        if (sysUser == null) {
            // 用户名或密码错误
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        if ("1".equals(sysUser.getStatus())) {
            throw new UserContLockedException("该用户账号被封禁，请联系管理员");
        }


        return new User(sysUser.getUsername(), sysUser.getPassword(), getUserAuthority(sysUser.getId()));
    }

    /**
     * 权限认证列表
     * @return 权限认证列表
     */
    public List<GrantedAuthority> getUserAuthority(Long userId) {
        // 格式
        /* ROLE_admin,ROLE_common,
           system:user:resetPwd,system:role:delete,system:user:list,system:menu:query,system:menu:list,
           system:menu:add,system:user:delete,system:role:list,system:role:menu,system:user:edit,
           system:user:query,system:role:edit,system:user:add,system:user:role,system:menu:delete,
           system:role:add,system:role:query,system:menu:edit
        */
        String authorityInfo = sysUserService.getUserAuthorityInfo(userId);
        log.info("authorityInfo:{}",authorityInfo);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authorityInfo);
    }
}
